import 'dart:convert';
import 'dart:developer';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:crypto/crypto.dart';

class UpLoad {
  /// 阿里云直接 上传图片
  static Future<String> upImg(String path) async {
    //构建policy, `expriation`设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了, `content-length-range`设置上传文件的大小限制
    String policyText = '{"expiration": "2050-01-01T12:00:00.000Z","conditions": [["content-length-range", 0, 1048576000]]}';
    List<int> policyTextUtf8 = utf8.encode(policyText);
    String policyBase64 = base64.encode(policyTextUtf8);
    List<int> policy = utf8.encode(policyBase64);


    // 利用OSSAccesskeySecret签名Policy
    List<int> key = utf8.encode('3JILwpbOLtpFE3BU9tZrzSoPwHnry3');
    List<int> signaturePre = Hmac(sha1, key).convert(policy).bytes;
    String signature = base64.encode(signaturePre);
    // 构建formData数据
    String dateTime = "${DateTime.now().millisecondsSinceEpoch.toString()}.jpg";
    FormData data = FormData.fromMap({
      'key': "userImg/" + dateTime,
      'policy': policyBase64,
      'OSSAccessKeyId': 'LTAI4GAgsimevog3Sdq9p9Wg',
      'success_action_status': '200',
      'signature': signature,
      'Content-Type':'image/jpeg',
      'file': await MultipartFile.fromFile(path,filename: dateTime),
    });
    if (path != "") {
      Response response = await Dio().post('http://cljp001.oss-cn-shenzhen.aliyuncs.com', data: data);
      if(response.statusCode == 200) {
        log('上传成功--------------http://cljp001.oss-cn-shenzhen.aliyuncs.com/userImg/$dateTime');
        return "http://cljp001.oss-cn-shenzhen.aliyuncs.com/userImg/$dateTime";
      }else {
        debugPrint('-------------------------图片上传失败');
        return "error";
      }
    } else {
      return "error";
    }
  }
}